import React from 'react'
import { View, Image, Clipboard, AppState } from 'react-native'
import {StackActions, NavigationActions } from "react-navigation"
import SplashScreen from "react-native-splash-screen"
import { Overlay, Projector } from "../_teaset"
import { Lt, NavTheme as Nav, Color, Label, Button, Images, Touch,  Navigator, Oview, Jpp, ImagePt, Dialog, Jx } from "../_utils"
import { Net, NET_GET, NET_RI } from "../_net"
import { eApp, FieldProps } from "./_home"
import { SegProjector, ViewScale } from '../_util';
import { eField } from './_efield';
import { Home, TouchApps } from './Home';
import { HomeSec } from './HomeSec';

// 签到/客服按钮
class TouchLR extends React.PureComponent{
    render(){
        const {onPress, source, title} = this.props;
        return <Touch 
            style={{margin:Lt.margin, }} 
            onPress = {onPress}
        >
            <View style = {{paddingHorizontal:Lt.pad,alignItems:"center",}}>
                <Image source={source}/>
                <Label style={{color:"white"}}>{title}</Label>
            </View>
        </Touch>
    }
}

// 搜索栏
export class TouchSearch extends React.PureComponent{
    render(){
        const {onPress, title} = this.props;
        return <Button.Pure1 style={{flex:1,height:32,marginHorizontal:Label.margin,}} onPress = {onPress}>
            <View style={{flex:1,borderRadius:16,backgroundColor:"white",flexDirection:"row", alignItems:"center",}}>
                <Image style={{marginHorizontal:Lt.margin}} source={Images.sousuo} />
                <Label style={{fontSize:Lt.c16, color:Color.c9}}>{title}</Label>
            </View>
        </Button.Pure1>;
    }
}

// 首页
export class Homes extends React.PureComponent{
    constructor(props){
        super(props);

        this.state = {
            fieldIdx:0,
        }

        this.goodslist = null;

        this.onAppStateChange = this.onAppStateChange.bind(this);
        this.onSign = this.onSign.bind(this);
        this.onSearch = this.onSearch.bind(this);
        this.onKefu = this.onKefu.bind(this);
        this.onChange = this.onChange.bind(this);
        this.onClipboard = this.onClipboard.bind(this);
    }
    static navigationOptions = {
        tabBarIcon : ({focused, tintColor})=><Image source={focused ? Images.shouye_2 : Images.shouye}/>
    }
    componentWillMount(){
        AppState.addEventListener('change',this.onAppStateChange);
    }
    componentDidMount(){
        SplashScreen.hide();
        Clipboard.getString().then(this.onClipboard);
    }
    componentWillUnmount(){
        AppState.removeEventListener('change', this.onAppStateChange);
    }
    onAppStateChange(nextAppState){
        if (nextAppState == 'active') {
            // if(!this.back2active){
            //     return;
            // }
            
            console.log("进入前台状态: " + this.routeName);
            // reset->登录界面 触发this->componentWillUnmount
            if(this.routeName == "GoodsDetail" || this.routeName == "ShareTo"){
                // 状态栏(是否合成)不好判断
                return;
            }
            // this.back2active = false;
            Clipboard.getString().then(this.onClipboard);
        }else if(nextAppState == 'background'){
            this.routeName = Navigator.getName(false);
            console.log("进入后台状态: " + this.routeName);
            
            // this.back2active = true;
        }
    }
    // 从后台进入前台 检测剪贴板
    onClipboard(str){
        if(str){
            if(str == this.clipboard){
                console.log("剪贴板重复: " + str);
                return;
            }
            this.clipboard = str;
            console.log("剪贴板: " + str);
        }else {
            return;
        }
        // let str = "￥ug9EbsdEBKr￥";
        // ¥   半角
        const i1 = str.indexOf("￥");
        const i2 = str.lastIndexOf("￥");
        if(i2 - i1 < 6){
            Dialog.toast("正在检测剪贴板");
            this.onAiSearchApps(str, appIdx=>{
                this.props.navigation.dispatch(StackActions.popToTop());
                const pushAction = StackActions.push({
                    routeName : "Search",
                    params : {appIdx, defaultValue:str, aiSearch : true},
                });
                this.props.navigation.dispatch(pushAction);
            });
            return;
        }
        Dialog.toast("正在检测淘口令");
        str = str.substr(i1, i2 - i1 + 1);
        console.log("截取: " + str);
        Net.request("taobao/convertTb?tkl=" + str, null, {NET_GET, NET_RI}).then(r=>{
            if(r.data && r.data.title){
                // this.clipboard = str;
                str = r.data.title;
                this.onAiSearch(str, ()=>{
                    this.props.navigation.dispatch(StackActions.popToTop());
                    const pushAction = StackActions.push({
                        routeName : "Search",
                        params : {appIdx : eApp.rdxs[eApp.TB], defaultValue:str, aiSearch : true},
                    });
                    this.props.navigation.dispatch(pushAction);
                });
            }
        });
    }
    // 搜索淘口令
    onAiSearch(str, cb){
        this.aiSearch && Overlay.hide(this.aiSearch);
        this.aiSearch = Overlay.show(<Oview.Msg modal={true} style={{width:Jpp.width * 3 / 5}}>
            <ViewScale ipt={ImagePt.zhinengsousuo} style={{width:Math.max(Jpp.width * 3 / 5, 300)}}>
                <Image source = {Images.zhinengsousuo}/>
            </ViewScale>
            <View style={{padding:20, justifyContent:"center", alignItems:"center"}}>
                <Label style={{fontSize:Lt.c16, color:Color.c3}} numberOfLines={4}  ellipsizeMode={"tail"}>{str}</Label>
            </View>
            <View style={{flexDirection: "row", height: Oview.btnHeight}}>
                <Button.Border1 title={"取消"} onPress={()=>this.aiSearch && Overlay.hide(this.aiSearch)} style = {{flex:1, borderWidth:0, color:Color.c6}}/>
                <Button.Border1 title={"搜索"} onPress={()=>{
                    cb && cb();
                    this.aiSearch && Overlay.hide(this.aiSearch);
                }} style = {{flex:1, borderWidth:0, color:Color.theme}}/>
            </View>
        </Oview.Msg>)
    }
    // 搜搜剪贴板(淘宝京东拼多多)
    onAiSearchApps(str, cb){
        this.aiSearch && Overlay.hide(this.aiSearch);
        this.aiSearch = Overlay.show(<Oview.Msg modal={true} style={{width:Jpp.width * 3 / 5}}>
            <ViewScale ipt={ImagePt.zhinengsousuo} style={{width:Math.max(Jpp.width * 3 / 5, 300)}}>
                <Image source = {Images.zhinengsousuo}/>
            </ViewScale>
            <View style={{padding:20, justifyContent:"center", alignItems:"center"}}>
                <Label style={{fontSize:Lt.c16, color:Color.c3}} numberOfLines={4}  ellipsizeMode={"tail"}>{str}</Label>
            </View>
            <View style={{flexDirection: "row", height: Oview.btnHeight}}>
                <Button.Border1 title={"取消"} onPress={()=>this.aiSearch && Overlay.hide(this.aiSearch)} style = {{flex:1, borderWidth:0, color:Color.c6}}/>
                {
                    eApp.idxs.map((v,i)=>{
                        return <Touch
                            key= {i} 
                            style={{flex:1, marginVertical:5}}
                            onPress={()=>{
                                cb && cb(i);
                                this.aiSearch && Overlay.hide(this.aiSearch);
                            }}
                        ><Image source={eApp.images[v]} /></Touch>
                    })
                }
            </View>
        </Oview.Msg>)
    }
    // 签到
    onSign(){
        Navigator.push("PageSign");
    }
    // 搜索
    onSearch(){
        Navigator.push("History");
    }
    // 客服
    onKefu(){
        Navigator.push("PageKefu");
    }
    // 首页 类目
    onChange(fieldIdx){
        this.setState({fieldIdx});
        this.goodslist && this.goodslist.setFieldIdx(fieldIdx);
    }
    render(){
        const app = eApp.HOME;
        return <View style = {{flex:1}}>
            <Nav.StateBar/>
            <View style={{backgroundColor:Color.theme, flexDirection:"row", alignItems:"center"}}>
                <TouchLR
                    source={Images.qiandao}
                    title={"签到"}
                    onPress={this.onSign}
                />
                <TouchSearch title = {"粘贴心仪宝贝标题"} onPress = {this.onSearch} />
                <TouchLR
                    source={Images.kefu}
                    title={"客服"}
                    onPress={this.onKefu}
                />
            </View>
            <SegProjector fields={eField[app].map(v=>v.name)} onChange={this.onChange} {...FieldProps}/>
            <Projector style={{flex:1}} index={(this.state.fieldIdx===0)?0:1}>
                <Home/>
                <HomeSec ref={r=>this.goodslist=r} app ={app}/>
            </Projector>
        </View>;
    }
}